package com.carl.guli.service;

import com.carl.guli.common.exception.BusinessException;
import com.carl.guli.common.util.CTUtils;
import com.carl.guli.mapper.AccountInfoMapper;
import com.carl.guli.model.AccountInfo;
import com.carl.guli.model.AccountInfoExample;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;

/**
 * Created by youzm on 2017/3/10.
 */
@Service
public class UserServiceImpl implements UserService {

    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);


    @Autowired
    AccountInfoMapper accountInfoMapper;

    public AccountInfo login(AccountInfo accountInfo) {
        AccountInfoExample example = new AccountInfoExample();
        example.createCriteria().andJobNumberEqualTo(accountInfo.getJobNumber());
        List<AccountInfo> accountInfos = accountInfoMapper.selectByExample(example);
        if (accountInfos.isEmpty()){
            throw new BusinessException("系统中不存在该账号,请联系管理员");
        }

        if (!CTUtils.encryptBasedDes(accountInfo.getPassword()).equals(accountInfos.get(0).getPassword())){
            throw new BusinessException("密码输入错误,请重新输入！");
        }
        logger.debug("[login] 登录成功" );
        return accountInfos.get(0);
    }

    public void setPassword(AccountInfo accountInfo) {
        accountInfoMapper.updateByPrimaryKeySelective(accountInfo);
    }

    public void initUserPassword() {
        AccountInfoExample example  = new AccountInfoExample();
        example.createCriteria().andPasswordIsNull();
        List<AccountInfo> accountInfos = accountInfoMapper.selectByExample(example);
        for (AccountInfo accountInfo: accountInfos){
            accountInfo.setPassword(CTUtils.encryptBasedDes(String.valueOf(accountInfo.getJobNumber())));
            accountInfoMapper.updateByPrimaryKeySelective(accountInfo);
        }
    }

    @Override
    public void modifyPassword(Integer accountId, String oldPassword, String password) {
        if (StringUtils.isEmpty(oldPassword) || StringUtils.isEmpty(password)){
            throw new BusinessException("原始密码或者新密码不能为空");
        }

        AccountInfo accountInfo = accountInfoMapper.selectByPrimaryKey(accountId);
        if (!accountInfo.getPassword().equals(CTUtils.encryptBasedDes(oldPassword))){
            throw new BusinessException("原始密码错误");
        }

        accountInfo.setPassword(CTUtils.encryptBasedDes(password));
        accountInfoMapper.updateByPrimaryKeySelective(accountInfo);
    }
}
